package com.budwk.app.sqfw.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.oss.models.SysOss;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.models.Sqfw_versionupdate;
import com.budwk.app.sqfw.services.OppoInterfaceService;
import com.budwk.app.sqfw.services.SqfwVersionupdateService;
import com.budwk.app.sqfw.services.VivoInterfaceService;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import jodd.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@IocBean
@At("/platform/sqfw/versionupdate")
@ApiDefinition(tag = "版本检测表")
@Slf4j
public class SqfwVersionupdateController {

    @Inject
    Dao dao;
    @Inject
    private SqfwVersionupdateService sqfwVersionupdateService;
    @Inject
    private SysOssService sysOssService;
    @Inject
    private VivoInterfaceService vivoInterfaceService;
    @Inject
    private OppoInterfaceService oppoInterfaceService;


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询版本检测表")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_versionupdate.class
    )
    @ApiResponses(
            implementation = Sqfw_versionupdate.class
    )
    @SaCheckPermission("sqfw.versionupdate")
    public Result<?> list(@Param("..") Sqfw_versionupdate bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        }

        if (bean.getVersionNumber() != null && Strings.isNotBlank(bean.getVersionNumber().toString())) {
            cnd.and("versionNumber", "=", bean.getVersionNumber());
        }

        if (bean.getVersionLink() != null && Strings.isNotBlank(bean.getVersionLink().toString())) {
            cnd.and("versionLink", "=", bean.getVersionLink());
        }

        if (bean.getHintRemark() != null && Strings.isNotBlank(bean.getHintRemark().toString())) {
            cnd.and("hintRemark", "=", bean.getHintRemark());
        }

        if (bean.getForceUpdate() != null && Strings.isNotBlank(bean.getForceUpdate().toString())) {
            cnd.and("forceUpdate", "=", bean.getForceUpdate());
        }

        if (bean.getUpdateType() != null && Strings.isNotBlank(bean.getUpdateType().toString())) {
            cnd.and("updateType", "=", bean.getUpdateType());
        }

        return Result.data(sqfwVersionupdateService.listPage(pageNo, pageSize, cnd));
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "新增版本检测表")
    @ApiFormParams(
            implementation = Sqfw_versionupdate.class
    )
    @ApiResponses
    @SLog(tag = "新增版本检测表", value = "${args[0].id}")
    @SaCheckPermission("sqfw.versionupdate.create")
    public Result<?> create(@Param("..") Sqfw_versionupdate sqfwVersionupdate, HttpServletRequest req) {
        sqfwVersionupdate.setCreatedBy(SecurityUtil.getUserId());
        if (!StringUtils.isNotBlank(sqfwVersionupdate.getUpdateType())) {
            sqfwVersionupdate.setUpdateType("app");
        }
        sqfwVersionupdateService.insert(sqfwVersionupdate);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改版本检测表")
    @ApiFormParams(
            implementation = Sqfw_versionupdate.class
    )
    @ApiResponses
    @SLog(tag = "修改版本检测表", value = "${args[0].id}")
    @SaCheckPermission("sqfw.versionupdate.update")
    public Result<?> update(@Param("..") Sqfw_versionupdate sqfwVersionupdate, HttpServletRequest req) {
        sqfwVersionupdate.setUpdatedBy(SecurityUtil.getUserId());
        if (!StringUtils.isNotBlank(sqfwVersionupdate.getUpdateType())) {
            sqfwVersionupdate.setUpdateType("app");
        }
        sqfwVersionupdateService.updateIgnoreNull(sqfwVersionupdate);
        return Result.success();
    }

    @At("/get")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取版本检测表")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SaCheckPermission("sqfw.versionupdate")
    @SLog(tag = "获取版本检测表",value = "${args[0]}")
    public Result<?> getData(@Param("id") String id, HttpServletRequest req) {
        Sqfw_versionupdate sqfwVersionupdate = sqfwVersionupdateService.fetch(id);
        if (sqfwVersionupdate == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        if (!StringUtils.isNotBlank(sqfwVersionupdate.getUpdateType())) {
            sqfwVersionupdate.setUpdateType("app");
        }
        return Result.data(sqfwVersionupdate);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除版本检测表")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "删除版本检测表", value = "${args[0]}")
    @SaCheckPermission("sqfw.versionupdate.delete")
    public Result<?> delete(@Param("id") String id, HttpServletRequest req) {
        Sqfw_versionupdate sqfwVersionupdate = sqfwVersionupdateService.fetch(id);
        if (sqfwVersionupdate == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        sqfwVersionupdateService.delete(id);
        req.setAttribute("_slog_msg", sqfwVersionupdate.getId());
        return Result.success();
    }


    @At("/upload")
    @Ok("json")
    @POST
    @ApiOperation(name = "上传版本")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "上传版本", value = "${args[0]}")
    @SaCheckPermission("sqfw.versionupdate.upload")
    public Result<?> upload(@Param("id") String id, @Param("file") String file, HttpServletRequest req) {

        SysOss sysOss = sysOssService.upload(FileUtil.file(file));
        String uploadresult = sysOss.getUrl();

        Sql sql = Sqls.create("update shequ.sqfw_versionupdate set uploadPath='" + uploadresult + "' where id='" + id + "'");
        dao.execute(sql);

        return Result.data(uploadresult);
    }

    @At("/download")
    @Ok("json")
    @POST
    @ApiOperation(name = "下载版本")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "下载版本", value = "${args[0]}")
    @SaCheckPermission("sqfw.versionupdate.download")
    public Result<?> download(@Param("id") String id, HttpServletRequest req) {
        Result result = Result.NEW();
        Sqfw_versionupdate versionupdate = sqfwVersionupdateService.fetch(id);
        result.addData(versionupdate.getUploadPath());

        return result;
    }


    @At("/newVersionData")
    @Ok("json")
    @POST
    @ApiOperation(name = "下载版本")
    @SLog(tag = "下载版本", value = "${args[0]}")
    //@SaCheckPermission("sqfw.versionupdate.download")
    public Result<?> newVersionData(@Param("updateType") String type, HttpServletRequest req) {
        Result result = Result.NEW();
        if (!Strings.isNotBlank(type)) {
            type = "app";
        }
        Sql sql = Sqls.create("SELECT * from shequ.sqfw_versionupdate where update_type='" + type + "' ORDER BY createdat desc ");
        List<JSONObject> list = new ArrayList<JSONObject>();
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                while (rs.next()) {

                    JSONObject obj = new JSONObject();
                    obj.put("id", rs.getString("id"));
                    obj.put("versionNumber", rs.getString("version_number"));
                    obj.put("versionLink", rs.getString("version_link"));
                    obj.put("hintRemark", rs.getString("hint_remark"));
                    obj.put("forceUpdate", rs.getString("force_update"));
                    obj.put("updateType", rs.getString("update_type"));

                    list.add(obj);
                }

                return list;
            }
        });//实体回调，不构建实体类
        Entity<Record> entity = dao.getEntity(Record.class);//Record是Nutz自带的一个类，查一下就知道了
        sql.setEntity(entity);
        dao.execute(sql);

        if (list.size() <= 0) {
            return Result.error();
        }

        return Result.data(list.get(0));
    }

    @At("/queryVivoLatestVersion")
    @Ok("json")
    @GET
    @ApiOperation(name = "查询vivo最新应用版本号")
    public Result<?> queryVivoLatestVersion() {
        return vivoInterfaceService.getVivoApplyLatestVersion();
    }

    @At("/queryOppoLatestVersion")
    @Ok("json")
    @GET
    @ApiOperation(name = "查询oppo最新应用版本号")
    public Result<?> queryOppoLatestVersion() throws Exception{
        return oppoInterfaceService.getOppoApplyLatestVersion();
    }
    @At
    @Ok("json:{ignoreNull:false}")
    @GET
    @ApiOperation(name = "查询荣耀app应用详细信息")
    public Result<?> queryHonorAppDetail() {
        return sqfwVersionupdateService.queryHonorAppDetail();
    }
}
